<?php

namespace app\admin\controller;

use app\admin\model\DismantlementSchedule;
use app\common\BaseHelper;
use think\Db;
use think\Exception;
use think\Request;

/**
 * 拆迁上报
 * Class Dismantlement
 * @package app\admin\controller
 */
class Dismantlement extends Base
{

    public function _initialize(){
        parent::_initialize();
        $this->redirect = 'admin/dismantlement/index';
    }

    public function index(){
        $request = $this->request;
        if($request->isAjax()){
            $param = $request->param();
            $model = model($this->model);
            // 每页起始条数
            //dump($param['start']);
            $start = $param['start'];
            // 每页显示条数
            $length = $param['length'];
            // 排序条件
            $columns = $param['order'][0]['column'];
            $order = $param['columns'][$columns]['data'].' '.$param['order'][0]['dir'];

            $where = $this->getFilterWhere($request);
            if($this->defaultWhere){
                //$model = $model->where($this->defaultWhere);
                $where = array_merge($where, $this->defaultWhere);
            }
            /*if($this->defaultOrder){
                $model = $model->order($this->defaultOrder);
            }*/

            $list = $model->where($where)->order($order)->limit($start, $length)->select();
            foreach ($list as &$item) {
                $Image = \app\admin\model\Image::where('relatedId',$item['id'])->find();
                $item['imgUrl'] = $Image['imgUrl'];
            }
            $count = $model->where($where)->count();

            $result = [
                'status' => '1',
                'draw' => $param['draw'],
                'data' => $list,
                'recordsFiltered' => $count,
                'recordsTotal' => $count,
            ];

            return json($result);
        }
        return parent::index();
    }

    public function add(Request $request){
        $areaMdl = new \app\admin\model\Area();
        $city = BaseHelper::makeOptions(
            $areaMdl,
            ['level' => 1],
            ['id' => 'asc']
        );

        $this->assign('city',$city);
        return $this->fetch();
    }

    public function addPost(Request $request){
        if($request->isPost()){
            $param = $request->param();
            if(empty($param['households'])){
                return $this->error('拆迁人姓名必填');
            }
            if(empty($param['address'])){
                return $this->error('拆迁地址必填');
            }
            if(empty($param['addressGeo'])){
                return $this->error('没有获取经纬度，请填写正确地址');
            }
            Db::startTrans();
            try{
                $Dismantlement = new \app\admin\model\Dismantlement();
                $id = BaseHelper::getUUID();
                $addressGeo = explode(',',$param['addressGeo']);
                $lat = $addressGeo[0];
                $lng = $addressGeo[1];
                $address = Common::getaddressbylatlng($lat,$lng);
                $Dismantlement->id = $id;
                $Dismantlement->households = $param['households'];
                $Dismantlement->province = $address['province'];
                $Dismantlement->city = $address['city'];
                $Dismantlement->area = $address['district'];
                $Dismantlement->address = $param['address'];
                $Dismantlement->lat = $lat;
                $Dismantlement->lng = $lng;
                $Dismantlement->save();

                //$this->insertSchedule($param,$id);
                $this->updateImg($param['imgIds'],$id);
                Db::commit();
                return $this->success('新增成功',$this->redirect);
            }catch (Exception $ex){
                Db::rollback();
                return $this->error($ex->getMessage());
            }
        }else{
            return $this->error('非法请求');
        }
    }

    public function edit(Request $request){
        $param = $request->param();
        if(empty($param['id'])){
            return $this->error('缺少参数');
        }
        $Dismantlement = \app\admin\model\Dismantlement::get($param['id']);
        $addressGeo = $Dismantlement->lat . ',' . $Dismantlement->lng;
        $Dismantlement['addressGeo'] = $addressGeo;
        $ScheduleList = DismantlementSchedule::where('disId',$Dismantlement->id)->select();
        $Dismantlement['scheduleList'] = $ScheduleList;
        $ImageList = \app\admin\model\Image::where('relatedId',$Dismantlement->id)->select();

        return $this->fetch('',[
            'info' => $Dismantlement,
            'imagesList' => $ImageList
        ]);

    }
    public function editPost(Request $request){
        if($request->isPost()){
            $param = $request->param();
            if(empty($param['editID'])){
                return $this->error('缺少参数');
            }
            Db::startTrans();
            try{
                $Dismantlement = \app\admin\model\Dismantlement::get($param['editID']);

                $this->updateImg($param['imgIds'],$Dismantlement->id);
                Db::commit();
                return $this->success('修改成功',$this->redirect);
            }catch (Exception $ex){
                Db::rollback();
                return $this->error($ex->getMessage());
            }
        }else{
            return $this->error('非法请求');
        }
    }

    //删除拆迁
    public function delPost(Request $request){
        if($request->isPost()){
            $param = $request->param();
            if(empty($param['id'])){
                return $this->error('缺少参数');
            }
            Db::startTrans();
            try{
                $Dismantlement = \app\admin\model\Dismantlement::where('id',$param['id'])->find();
                if($Dismantlement){
                    $Dismantlement->delete();
                    DismantlementSchedule::where('disId',$Dismantlement->id)->delete();
                    Db::commit();
                    return $this->success('删除成功');
                }
            }catch (Exception $ex){
                Db::rollback();
                return $this->error('删除失败');
            }

        }else{
            return $this->error('非法请求');
        }
    }

    private function updateImg($imgIds,$relatedId){
        if(is_array($imgIds)){
            $Image = new \app\admin\model\Image();
            $update = [];
            foreach ($imgIds as $v){
                array_push($update,['id'=>$v,'relatedId'=>$relatedId]);
            }
            $Image->isUpdate()->saveAll($update);
        }else{
            $Image = \app\admin\model\Image::get($imgIds);
            $Image->relatedId = $relatedId;
            $Image->save();
        }
    }
}